package com.tang.provider;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

/**
 * SpringBoot定制Jackson ObjectMapper
 *
 * @author cfpu003
 */
@Configuration
public class CustomJacksonObject {

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer customJackson() {
        return new Jackson2ObjectMapperBuilderCustomizer() {
            public void customize(
                    Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {
                // 不返回null值
                jacksonObjectMapperBuilder
                        .serializationInclusion(Include.NON_NULL);
                jacksonObjectMapperBuilder
                        .serializationInclusion(Include.NON_EMPTY);
                // 时间格式化
                jacksonObjectMapperBuilder
                        .simpleDateFormat("yyyy-MM-dd hh:mm:ss");
                // 设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性
                jacksonObjectMapperBuilder.failOnUnknownProperties(false);
                // jacksonObjectMapperBuilder.propertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
            }
        };
    }

    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        // 防止重复引用导致的序列化失败
        objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
        // 为null的字段不返回
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        return objectMapper;

    }

}
